import React, {Component, Fragment} from 'react'
import {connect} from 'dva'
import {Card, Col, DatePicker, Icon, Row, Tabs, Tooltip} from 'antd'
import numeral from 'numeral'
import {Bar, ChartCard, Field, MiniArea, MiniBar, MiniProgress, Pie, yuan} from 'components/Charts'
import Trend from 'components/Trend'
import ChinaMap from './componets/ChinaMap'
import Line from './componets/Line'
import {getTimeDistance} from 'utils'

import styles from './index.less'

const { TabPane } = Tabs
const { RangePicker } = DatePicker

const Yuan = ({ children }) => (
  <span
    dangerouslySetInnerHTML={{ __html: yuan(children) }} /* eslint-disable-line react/no-danger */
  />
)

@connect(({ chart, loading }) => ({
  chart,
  loading: loading.effects['chart/fetch'],
}))
export default class Analysis extends Component {
  state = {
    salesType: 'all',
    currentTabKey: '',
    rangePickerValue: getTimeDistance('year'),
  }

  componentWillUnmount() {
    const { dispatch } = this.props
    dispatch({
      type: 'chart/clear',
    })
  }

  handleChangeSalesType = e => {
    this.setState({
      salesType: e.target.value,
    })
  }

  handleTabChange = key => {
    this.setState({
      currentTabKey: key,
    })
  }

  handleRangePickerChange = rangePickerValue => {
    this.setState({
      rangePickerValue,
    })

    const { dispatch } = this.props
    dispatch({
      type: 'chart/fetchSalesData',
      payload: {
        start: rangePickerValue[0].format('YYYY-MM-DD'),
        end: rangePickerValue[1].format('YYYY-MM-DD'),
      },
    })
  }

  selectDate = type => {
    const rangePickerValue = getTimeDistance(type)
    this.setState({
      rangePickerValue,
    })

    const { dispatch } = this.props
    dispatch({
      type: 'chart/fetchSalesData',
      payload: {
        start: rangePickerValue[0].format('YYYY-MM-DD'),
        end: rangePickerValue[1].format('YYYY-MM-DD'),
      },
    })
  }

  isActive(type) {
    const { rangePickerValue } = this.state
    const value = getTimeDistance(type)
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return
    }
    if (
      rangePickerValue[0].isSame(value[0], 'day') &&
      rangePickerValue[1].isSame(value[1], 'day')
    ) {
      return styles.currentDate
    }
  }

  render() {
    const { rangePickerValue } = this.state
    const { chart, loading } = this.props
    const {
      saleAmountStat = {},
      orderStat,
      visitData,
      saleProgress,
      operatorStat,
      incomingLine,
      saleData,
      incomeData,
      saleRankings,
      data,
      geoData,
    } = chart

    const salesExtra = (
      <div className={styles.salesExtraWrap}>
        <div className={styles.salesExtra}>
          <a className={this.isActive('today')} onClick={() => this.selectDate('today')}>
            今日
          </a>
          <a className={this.isActive('week')} onClick={() => this.selectDate('week')}>
            本周
          </a>
          <a className={this.isActive('month')} onClick={() => this.selectDate('month')}>
            本月
          </a>
          <a className={this.isActive('year')} onClick={() => this.selectDate('year')}>
            全年
          </a>
        </div>
        <RangePicker
          value={rangePickerValue}
          onChange={this.handleRangePickerChange}
          style={{ width: 256 }}
        />
      </div>)

    const topColResponsiveProps = {
      xs: 24,
      sm: 12,
      md: 12,
      lg: 12,
      xl: 6,
      style: { marginBottom: 24 },
    }

    const LineProps = {
      source: incomingLine,
    }

    const progressDescription = saleProgress.accomplishedStatus === "finished"
      ? (<Trend>
        本月销售目标已经完成了
      </Trend>)
      : (<Trend>
        还差
        <span className={styles.trendText}>{saleProgress.amount ? saleProgress.amount : '80.00万'}</span> 完成销售目标
      </Trend>)

    return (
      <Fragment>
        <Row gutter={24}>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="总销售额"
              loading={loading}
              action={
                <Tooltip title="销售额统计">
                  <Icon type="info-circle-o" />
                </Tooltip>
              }
              total={() => <Yuan>{(saleAmountStat||{}).totalAmount}</Yuan>}
              footer={<Field label="日均销售额" value={`￥${numeral((saleAmountStat||{}).dayAverage).format('0,0')}`} />}
              contentHeight={46}
            >
              <Trend flag="up" style={{ marginRight: 16 }}>
                周同比
                <span className={styles.trendText}>{(saleAmountStat||{}).weekCompare ? (saleAmountStat||{}).weekCompare : 0}%</span>
              </Trend>
              <Trend flag="down">
                日环比
                <span className={styles.trendText}>{(saleAmountStat||{}).dayCompare ? (saleAmountStat||{}).dayCompare : 0}%</span>
              </Trend>
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="总粉丝数"
              loading={loading}
              action={
                <Tooltip title="最近十五天进粉量统计">
                  <Icon type="info-circle-o" />
                </Tooltip>
              }
              total={numeral(visitData.fansCount).format('0,0')}
              footer={
                <div style={{ whiteSpace: 'nowrap', overflow: 'hidden' }}>
                  <Trend flag={visitData.todayCount > visitData.yesTodayCount ? 'up' : 'down'}
                    style={{ marginRight: 16 }}>
                    今日进粉
                    <span className={styles.trendText}>{visitData.todayCount ? visitData.todayCount : 0}</span>
                  </Trend>
                  <Trend flag={visitData.yesTodayCount < visitData.todayCount ? 'down' : 'up'}>
                    昨日进粉
                    <span className={styles.trendText}>{visitData.yesTodayCount ? visitData.yesTodayCount : 0}</span>
                  </Trend>
                </div>
              }
              contentHeight={46}
            >
              <MiniArea color="#975FE4" data={visitData.customerCountVOS} />
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="订单数"
              loading={loading}
              action={
                <Tooltip title="最近十五天订单统计">
                  <Icon type="info-circle-o" />
                </Tooltip>
              }
              total={numeral(orderStat.orderNum).format('0,0')}
              footer={
                <div style={{ whiteSpace: 'nowrap', overflow: 'hidden' }}>
                  <Trend style={{ marginRight: 16 }}>
                    复购率
                    <span className={styles.trendText}>{orderStat.rePurchaseRate ? orderStat.rePurchaseRate : 0}%</span>
                  </Trend>
                  <Trend flag={orderStat.monthlyGrowth > 0 ? 'up' : 'down'} style={{ marginRight: 16 }}>
                    月增长
                    <span className={styles.trendText}>{orderStat.monthlyGrowth ? orderStat.monthlyGrowth : 0}%</span>
                  </Trend>
                </div>
              }
              contentHeight={46}
            >
              <MiniBar data={orderStat.dailyGrowthList} />
            </ChartCard>
          </Col>
          <Col {...topColResponsiveProps}>
            <ChartCard
              bordered={false}
              title="本月销售进度"
              loading={loading}
              action={
                <Tooltip title="本月销售进度统计">
                  <Icon type="info-circle-o" />
                </Tooltip>
              }
              total={saleProgress.salePercent ? saleProgress.salePercent : 0 + "%"}
              footer={
                <div style={{ whiteSpace: 'nowrap', overflow: 'hidden' }}>
                  {progressDescription}
                </div>
              }
              contentHeight={46}
            >
              <MiniProgress percent={saleProgress.salePercent ? saleProgress.salePercent : 0} strokeWidth={8} target={saleProgress.targetPercent ? saleProgress.targetPercent : 80}
                color="#13C2C2" />
            </ChartCard>
          </Col>
        </Row>

        <Row gutter={24}>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <Card
              loading={loading}
              className={styles.salesCard}
              bordered={false}
              title="全平台统计"
              bodyStyle={{ padding: 24 }}
              style={{ minHeight: 500 }}>
              <div>
                <Tabs tabPosition={'bottom'}>
                  <TabPane tab={'运营号统计'} key={'operatorStat'}>
                    <div style={{ height: 294 }}>
                      <Pie
                        colors={["rgb(47, 194, 91)", "rgb(240, 72, 100)", "rgb(250, 204, 20)", "rgb(24, 144, 255)"]}
                        hasLegend
                        style={{ marginTop: 20 }}
                        subTitle="运营号数量"
                        total={() => <span>{operatorStat.reduce((pre, now) => parseInt(now.y) + pre, 0)}</span>}
                        data={operatorStat}
                        height={250}
                      />
                    </div>
                  </TabPane>
                  <TabPane tab={'今日进线'} key={'joinToday'}>
                    <Line {...LineProps} />
                  </TabPane>
                </Tabs>
              </div>
            </Card>
          </Col>
          <Col xl={12} lg={24} md={24} sm={24} xs={24}>
            <Card
              loading={loading}
              className={styles.salesCard}
              bordered={false}
              title="成交客户分布图"
              bodyStyle={{ padding: 24 }}
              style={{ minHeight: 500 }}>
              <ChinaMap data={data} geoData={geoData} />
            </Card>
          </Col>
        </Row>

        <Card loading={loading} bordered={false} style={{ marginTop: 24 }} bodyStyle={{ padding: 0 }}>
          <div className={styles.salesCard}>
            <Tabs tabBarExtraContent={salesExtra} size="large" tabBarStyle={{ marginBottom: 24 }}>
              <TabPane tab="销售额" key="sales">
                <Row>
                  <Col xl={16} lg={12} md={12} sm={24} xs={24}>
                    <div className={styles.salesBar}>
                      <Bar height={295} title="销售额趋势" data={saleData} />
                    </div>
                  </Col>
                  <Col xl={8} lg={12} md={12} sm={24} xs={24}>
                    <div className={styles.salesRank}>
                      <h4 className={styles.rankingTitle}>员工销售排行</h4>
                      <ul className={styles.rankingList}>
                        {saleRankings.map((item, i) => (
                          <li key={item.username}>
                            <span className={i < 3 ? styles.active : ''}>{i + 1}</span>
                            <span>{item.username}</span>
                            <span>{numeral(item.totalAmount).format('0,0')}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  </Col>
                </Row>
              </TabPane>
              <TabPane tab="进粉量" key="views">
                <Row>
                  <Col xl={16} lg={12} md={12} sm={24} xs={24}>
                    <div className={styles.salesBar}>
                      <Bar height={292} title="进粉量趋势" data={incomeData} />
                    </div>
                  </Col>
                  <Col xl={8} lg={12} md={12} sm={24} xs={24}>
                    <div className={styles.salesRank}>
                      <h4 className={styles.rankingTitle}>员工销售排行</h4>
                      <ul className={styles.rankingList}>
                        {saleRankings.map((item, i) => (
                          <li key={item.username}>
                            <span className={i < 3 ? styles.active : ''}>{i + 1}</span>
                            <span>{item.username}</span>
                            <span>{numeral(item.totalAmount).format('0,0')}</span>
                          </li>
                        ))}
                      </ul>
                    </div>
                  </Col>
                </Row>
              </TabPane>
            </Tabs>
          </div>
        </Card>
      </Fragment>
    )
  }
}
